<template>
  <div class="authentication_company">
    <p class="complement-company-data tc" v-if="!isEnter && !isActivate">
      <a-alert
        class="inline-b"
        message="该企业还没有入驻平台，请填写以下资料，申请入驻平台"
        type="warning"
        show-icon
      />
    </p>
    <div class="form_wrapper">
      <c-form
        v-model="form"
        :col="{ labelCol: { span: 10 }, wrapperCol: { span: 14 } }"
        ref="form"
        :data="formData"
        :rules="formRules"
        @submit="submit"
        :submitLoading="submitLoading"
      >
        <template v-slot:companyName="{ change }">
          <a-auto-complete
            v-model.trim="form.companyName"
            :disabled="!isEnter"
            placeholder="请输入企业名称"
            option-label-prop="title"
            @search="onSearchCompany"
            @change="change('companyName')"
          >
            <template slot="dataSource">
              <a-select-option
                v-for="item in companySelectList"
                :key="item.companyName"
                :title="item.companyName"
              >
                {{ item.companyName }}
              </a-select-option>
            </template>
          </a-auto-complete>
        </template>
        <template v-slot:categorys>
          <c-category v-model="form.categorys" multiple></c-category>
        </template>
        <template v-slot:companyCityCode>
          <c-city v-model="form.companyCityCode" />
        </template>
        <template v-slot:businessLicense>
          <template v-if="isActivate">
            <img
              v-if="form.businessLicenseUrl && !form.businessLicense"
              :src="form.businessLicenseUrl"
              @click="activateChangeBusinessLicense"
              class="businessLicense-activate"
              width="128"
              height="128"
              alt=""
            />
            <c-upload
              v-show="!form.businessLicenseUrl || form.businessLicense"
              ref="businessLicense"
              type="image"
              @change="changeBusinessLicense"
              accept="image/*"
            ></c-upload>
          </template>
          <template v-else>
            <c-upload
              type="image"
              @change="changeBusinessLicense"
              accept="image/*"
            ></c-upload>
          </template>
        </template>
        <template v-slot:authorizationFile>
          <c-upload
            type="image"
            @change="changeAuthorizationFile"
            accept="image/*"
          ></c-upload>
          <span
            class="title primary cursor-pointer"
            @click="downloadAuthorization"
            >下载模板</span
          >
        </template>
        <template v-slot:registeredCapital>
          <a-input
            v-model="form.registeredCapital"
            suffix="万元"
            placeholder="请输入注册资本"
          />
        </template>
        <template v-slot:agreement>
          <div class="agreement flex flex-align-c">
            <a-checkbox v-model="agreementChecked"></a-checkbox>
            <span class="text"> 我已阅读并同意 </span>
            <c-button
              type="link"
              @click="
                viewAgreement('聚点商城平台交易服务协议', 'serviceContract')
              "
              >《聚点商城平台交易服务协议》</c-button
            >
            <c-button
              type="link"
              @click="
                viewAgreement(
                  '聚点商城平台买家交易规则',
                  'buyerTransactionRules'
                )
              "
              v-if="form.companyDirection === 1 || form.companyDirection === 3"
              >、《聚点商城平台买家交易规则》</c-button
            >
            <c-button
              type="link"
              @click="
                viewAgreement(
                  '聚点商城平台卖家交易规则',
                  'sellerTransactionRules'
                )
              "
              v-if="form.companyDirection === 2 || form.companyDirection === 3"
              >、《聚点商城平台卖家交易规则》</c-button
            >
          </div>
        </template>
      </c-form>
    </div>
    <c-modal title="" v-model="viewAgreementVisible" :width="700" noFooter>
      <!-- <iframe
        :src="agreementData.url"
        frameborder="0"
        width="100%"
        height="600"
      ></iframe> -->
      <component
        :is="agreementName"
        style="max-height: 600px;overflow: auto;"
      />
    </c-modal>
  </div>
</template>

<script>
import { getAllCompanys } from "@/api/company";
import {
  userJoinCompany,
  authNewCompany,
  checkAuthCompany
} from "@/api/certify";
import cUpload from "@/components/upload";
import { assign } from "lodash";
import { companyactivatebyadmin } from "@/api/activate";
import serviceContract from "@/page/agreement/serviceContract";
import buyerTransactionRules from "@/page/agreement/buyerTransactionRules";
import sellerTransactionRules from "@/page/agreement/sellerTransactionRules";

const enterprise = [
  {
    label: "企业名称",
    prop: "companyName",
    slot: "companyName"
  }
];

export default {
  components: {
    cUpload,
    serviceContract,
    buyerTransactionRules,
    sellerTransactionRules
  },
  props: {
    // 激活时回填企业信息
    companyData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    let businessLicenseRules = (rule, value, callback) => {
      // 激活时不做必填判断
      if (this.isActivate) {
        callback();
      } else {
        if (this.form.businessLicense) {
          callback();
        } else {
          callback(new Error("请上传营业执照"));
        }
      }
    };
    return {
      agreementName: undefined,
      form: {
        companyName: null,
        creditNum: null,
        legalpersonName: null,
        legalpersonId: null,
        introducer: null,
        categorys: [],
        companyCityCode: null,
        registeredCapital: undefined,
        companyDirection: 1,
        businessLicense: null,
        authorizationFile: null
      },
      formRules: {
        companyName: [
          { required: true, message: "请输入企业名称", trigger: "change" }
        ],
        legalpersonName: [
          { required: true, message: "请输入法定代表人姓名", trigger: "change" }
        ],
        legalpersonId: [
          { required: true, validator: this.$vd.idCard, trigger: "change" }
        ],
        introducer: [
          { required: true, message: "请输入推荐人", trigger: "change" }
        ],
        creditNum: [
          { required: true, message: "请输入社会信用代码", trigger: "change" }
        ],
        businessLicense: [
          { required: true, validator: businessLicenseRules, trigger: "change" }
        ],
        authorizationFile: [
          { required: true, message: "请上传授权书", trigger: "change" }
        ]
      },
      allCompanyList: [],
      companySelectList: [],
      isEnter: true,
      submitLoading: false,
      agreementChecked: true,
      agreementData: {
        title: undefined,
        url: undefined
      },
      viewAgreementVisible: false
    };
  },
  computed: {
    // 是否激活
    isActivate() {
      return this.$route.name === "activateCompany";
    },
    formData() {
      let res;
      if (this.isEnter) {
        res = enterprise;
      } else {
        res = enterprise.concat([
          {
            label: "社会信用代码",
            prop: "creditNum"
          },
          {
            label: "法定代表人姓名",
            prop: "legalpersonName"
          },
          {
            label: "法定代表人身份证号",
            prop: "legalpersonId"
          },
          {
            label: "推荐人",
            prop: "introducer"
          },
          {
            label: "企业所在城市",
            prop: "companyCityCode",
            slot: "companyCityCode"
          },
          {
            label: "注册资本",
            prop: "registeredCapital",
            slot: "registeredCapital"
          },
          {
            label: "企业身份",
            prop: "companyDirection",
            disabled: this.isActivate,
            type: "radio",
            typeData: this.isActivate
              ? [
                  {
                    label: "买家",
                    value: 1
                  },
                  {
                    label: "卖家",
                    value: 2
                  },
                  {
                    label: "买家和卖家",
                    value: 3
                  }
                ]
              : [
                  {
                    label: "买家",
                    value: 1
                  }
                ]
          },
          {
            label: "交易品种",
            prop: "categorys",
            slot: "categorys"
          },
          {
            label: "营业执照",
            prop: "businessLicense",
            slot: "businessLicense"
          },
          {
            label: "认证授权书",
            prop: "authorizationFile",
            slot: "authorizationFile"
          },
          {
            label: " ",
            colon: false,
            slot: "agreement"
          }
        ]);
      }
      res = res.concat([
        {
          label: " ",
          colon: false,
          type: "submit",
          disabled: !this.agreementChecked,
          submitText: "提交认证"
        }
      ]);
      return res;
    }
  },
  methods: {
    // 激活企业更换营业执照
    activateChangeBusinessLicense() {
      this.$refs.businessLicense.clickInput();
    },
    // 下载授权模板
    downloadAuthorization() {
      var iframe = document.createElement("iframe");
      iframe.src = this.$globalSite.authorization;
      iframe.style.display = "none";
      document.body.appendChild(iframe);
    },
    // 根据搜索的内容查找匹配的企业
    onSearchCompany(searchText) {
      let companyList = this.allCompanyList;
      this.companySelectList = searchText
        ? companyList.filter(this.createStateFilter(searchText))
        : [];
    },
    createStateFilter(queryString) {
      return state => {
        return (
          state.companyName.toLowerCase().indexOf(queryString.toLowerCase()) >=
          0
        );
      };
    },
    // 获取所有企业
    queryAllCompany() {
      getAllCompanys().then(res => {
        this.allCompanyList = res;
      });
    },
    // 获取营业执照
    changeBusinessLicense(file) {
      if (this.isActivate) this.form.businessLicenseUrl = undefined;
      this.form.businessLicense = file;
    },
    // 获取认证授权书
    changeAuthorizationFile(file) {
      this.form.authorizationFile = file;
    },
    // 查看协议
    viewAgreement(title, url) {
      this.agreementData.title = title;
      // this.agreementData.url = "http://192.168.0.230:8080/" + url + ".html";
      this.viewAgreementVisible = true;
      this.agreementName = url;
    },
    // 校验
    submit() {
      this.$refs.form.validated().then(() => {
        let _this = this;
        this.$confirm({
          title: "温馨提示",
          content: "请核实信息，是否确认提交?",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            return new Promise(resolve => {
              _this.submitLoading = true;
              if (_this.isEnter) {
                // 校验输入的企业是否已入驻
                checkAuthCompany({
                  companyName: _this.form.companyName
                })
                  .then(res => {
                    _this.isEnter = true;
                    userJoinCompany({
                      companyId: res.id
                    })
                      .then(() => {
                        _this.$emit("success");
                      })
                      .finally(() => {
                        _this.submitLoading = false;
                      });
                  })
                  .catch(err => {
                    // 未认证的企业
                    if (
                      err.code === _this.$globalSite.errorCode.companyNoAuth
                    ) {
                      _this.isEnter = false;
                      _this.$emit("noEnter");
                    }
                    _this.submitLoading = false;
                  });
              } else {
                let f = new FormData();
                f.append("companyName", _this.form.companyName);
                f.append("creditNum", _this.form.creditNum);
                if (_this.form.registeredCapital)
                  f.append("registeredCapital", _this.form.registeredCapital);
                f.append("companyDirection", _this.form.companyDirection);
                f.append("categorys", _this.form.categorys);
                f.append(
                  "companyCityCode",
                  _this.form.companyCityCode
                    ? _this.form.companyCityCode[1]
                    : ""
                );
                // 激活时传businessLicenseUrl，否则传businessLicense
                if (_this.form.businessLicenseUrl) {
                  f.append("businessLicenseUrl", _this.form.businessLicenseUrl);
                } else {
                  f.append("businessLicense", _this.form.businessLicense);
                }
                f.append("authorizationFile", _this.form.authorizationFile);
                f.append("legalpersonName", _this.form.legalpersonName);
                f.append("legalpersonId", _this.form.legalpersonId);
                f.append("introducer", _this.form.introducer);
                let request = _this.isActivate
                  ? companyactivatebyadmin
                  : authNewCompany;
                request(f)
                  .then(res => {
                    _this.$emit("success", {
                      companyName: _this.form.companyName,
                      flowId: res.flowId
                    });
                  })
                  .finally(() => {
                    _this.submitLoading = false;
                  });
              }
              resolve();
            });
          }
        });
      });
    }
  },
  created() {
    // 重新认证，回填企业名称
    if (this.$route.query.name) this.form.companyName = this.$route.query.name;
    if (this.isActivate) {
      this.isEnter = false;
      assign(this.form, this.companyData);
      this.form.businessLicense = null;
      this.form.businessLicenseUrl = this.companyData.businessLicense;
    } else {
      this.queryAllCompany();
    }
  }
};
</script>

<style lang="scss" scoped>
.complement-company-data {
  margin-bottom: 24px;
}
.agreement {
  transform: translateX(-30%);
  width: max-content;
  .text {
    flex-shrink: 0;
    padding-left: 10px;
  }
  .c-button {
    display: inline-block;
    padding: 0;
  }
}
.businessLicense-activate {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}
</style>
